package com.haodai.vip.tomcat.server;

import com.haodai.vip.tomcat.utils.LogUtils;
import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;

public final class HttpServer {

    private static HttpServer server = new HttpServer();

    public Map<String, Servlet> servletMap = new HashMap<>();
    public Map<String, HttpSession> sessionMap = new HashMap<>();

    private final int serverPort;
    private final int maxConnectionQueue;

    private HttpServer(){
        String packName = HttpServer.class.getPackage().getName();
        InputStream in = HttpServer.class.getClassLoader().getResourceAsStream(packName.replaceAll("\\.", "/")+"/"+ Config.Server.CONFIG_PATH);
        Properties prop = new Properties();
        try {
            prop.load(in);
            serverPort = Integer.parseInt(prop.getProperty("SERVER_PORT"));
            maxConnectionQueue = Integer.parseInt(prop.getProperty("MAX_CONNECTION_QUEUE"));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("读取服务器配置文件出错");
        }
    }

    public static HttpServer getInstance(){
        return server;
    }

    public void start(){
            ServerSocket serverSocket = createSocket();
            while (true){
                try {
                    Socket socket = serverSocket.accept();
                    new ServerThread(this, socket).start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    }

    private ServerSocket createSocket(){
        ServerSocket serverSocket;
        try {
            serverSocket = new ServerSocket(serverPort);//, maxConnectionQueue, InetAddress.getByName("127.0.0.1"));
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("创建服务器失败");
        }
        return serverSocket;
    }

    public void addController(String path, Servlet servlet){
        servletMap.put(path, servlet);
    }

    public Map<String, Servlet> getControllerMap(){
        return this.servletMap;
    }
}
